/**
 * @Author       : oak-c
 * @Date         : 2021-01-18 19:01:58
 * @Description  :
 * @LastEditors  : oak-c
 * @LastEditTime : 2021-01-20 11:12:04
 * @FilePath     : /src/modules/filters/http.filter.ts
 */
import { timestamp } from '@/util'
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common'
import moment from 'moment'
import { CustomLoggerService } from '../logger'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
    constructor(private readonly logger: CustomLoggerService) {}
    public catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp()
        const response = ctx.getResponse()
        const request = ctx.getRequest()
        const status = exception.getStatus()
        const exceptionResponse: string | Record<string, any> = exception.getResponse()

        let responseStatus = 200
        const res = {
            flag: -1,
            message: '未知错误',
            timestamp: timestamp(),
            path: request.url,
        }
        if (typeof exception?.message === 'string') {
            res.message = exception.message
        }
        if (typeof exceptionResponse === 'string') {
            res.message = exceptionResponse
        } else if (typeof exceptionResponse === 'object') {
            if (typeof exceptionResponse.message === 'string') {
                res.message = exceptionResponse.message
            } else if (Array.isArray(exceptionResponse.message)) {
                res.message = exceptionResponse.message[0]
            }
        }
        switch (status) {
            case 400:
                res.flag = 9999
                break
            case 401:
                res.message = '登录态已失效，请重新登录。'
                res.flag = 9000
                break
            case 403:
                res.message = '您没有权限。'
                res.flag = 9997
                break
            case 404:
                res.message = '接口有误，请联系管理员！'
                res.flag = 9998
                break
            default:
                responseStatus = status
                break
        }
        this.logger.filterLog(host, res.flag === -1 ? exception : null, res.message)
        response.status(responseStatus).json(res)
    }
}
